package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.view.View;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ActorAdapter;
import flc.ast.adapter.RecommendAdapter;
import flc.ast.bean.ActorBean;
import flc.ast.databinding.ActivityMovieDetailBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.api.StkResApi;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseWebviewActivity;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.bean.StkResBean;

public class MovieDetailActivity extends BaseAc<ActivityMovieDetailBinding> {

    public static StkResBean stkResBean;
    private ActorAdapter actorAdapter;
    private RecommendAdapter recommendAdapter;
    private boolean isCollect;

    @Override
    protected int onCreate() {
        return R.layout.activity_movie_detail;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivMovieDetailBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivMovieDetailShare.setOnClickListener(this);
        mDataBinding.ivCollect.setOnClickListener(this);

        mDataBinding.rvActorList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        actorAdapter = new ActorAdapter();
        mDataBinding.rvActorList.setAdapter(actorAdapter);

        mDataBinding.rvRecommendList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        recommendAdapter = new RecommendAdapter();  // 修改为新的适配器名
        mDataBinding.rvRecommendList.setAdapter(recommendAdapter);
        recommendAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMovieDetailShare://分享
                IntentUtil.shareText(mContext, stkResBean.getUrl());
                break;
            case R.id.ivCollect://收藏
                List<StkResBean> collectList = AppSpUtils.getCollectList();
                if (collectList == null) collectList = new ArrayList<>();
                if (isCollect) {
                    // 如果已收藏,则取消收藏
                    for (int i = 0; i < collectList.size(); i++) {
                        if (collectList.get(i).getUrl().equals(stkResBean.getUrl())) {
                            collectList.remove(i);
                            break;
                        }
                    }
                } else {
                    // 如果未收藏,则添加到收藏列表开头
                    collectList.add(0, stkResBean);
                }
                AppSpUtils.saveCollectList(collectList);
                getCollectStatus();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        StkResBean bean = (StkResBean) adapter.getItem(position);
        MovieDetailActivity.stkResBean = bean;
        startActivity(MovieDetailActivity.class);
        finish();
    }

    @Override
    protected void initData() {
        Glide.with(mContext).load(stkResBean.getThumbUrl()).into(mDataBinding.ivDetailBackground);
        Glide.with(mContext).load(stkResBean.getThumbUrl()).into(mDataBinding.ivDetailImg);
        mDataBinding.tvDetailName.setText(stkResBean.getName());

        String str = new Gson().toJson(stkResBean.getExtra());
        List<ActorBean> list = new ArrayList<>();
        if (str != null && !str.equals("\"\"")) {
            mDataBinding.tvActorList.setVisibility(View.VISIBLE);
            try {
                JSONObject extra = new JSONObject(str);
                JSONArray actorList = extra.optJSONArray("actorList");
                if (actorList != null) {
                    for (int i = 0; i < actorList.length(); i++) {
                        JSONObject item = actorList.getJSONObject(i);
                        if (!item.getString("role").equals("导演")) {
                            list.add(new ActorBean(item.optString("name"), item.optString("img"), item.optString("role")));
                        }
                    }
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        } else {
            mDataBinding.tvActorList.setVisibility(View.GONE);
        }

        String tag = "";
        for (int i = 0; i < stkResBean.getTagNameList().size(); i++) {
            if (i == stkResBean.getTagNameList().size() - 1) {
                tag += stkResBean.getTagNameList().get(i);
            } else {
                tag += stkResBean.getTagNameList().get(i) + " | ";
            }
        }
        mDataBinding.tvDetailType.setText(tag);

        //评分
        double score = (double) stkResBean.getScore_total() / (stkResBean.getScore_count() == 0 ? 1 : stkResBean.getScore_count());
        String formattedNumber = String.format("%.2f", score);
        mDataBinding.tvDetailScore.setText(formattedNumber);
        if (score > 8) {
            mDataBinding.zzratingbar.setRating(5);
        } else if (score > 6) {
            mDataBinding.zzratingbar.setRating(4);
        } else if (score > 4) {
            mDataBinding.zzratingbar.setRating(3);
        } else if (score > 2) {
            mDataBinding.zzratingbar.setRating(2);
        } else {
            mDataBinding.zzratingbar.setRating(1);
        }

        mDataBinding.tvDetailDesc.setText(stkResBean.getDesc());

        actorAdapter.setList(list);

        getRecommendData();
        getCollectStatus();
    }

    private void getRecommendData() {
        StkResApi.getTagResourceList(this, AppConfig.RECOMMEND_DATA, StkResApi.createParamMap(0, 10), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        recommendAdapter.setList(result);
                    }
                }
            }
        });
    }

    private void getCollectStatus() {
        List<StkResBean> collectList = AppSpUtils.getCollectList();
        String currentUrl = stkResBean.getUrl();

        isCollect = false;
        if (collectList != null) {
            for (StkResBean item : collectList) {
                if (currentUrl.equals(item.getUrl())) {
                    isCollect = true;
                    break;
                }
            }
        }
        mDataBinding.ivCollect.setImageResource(isCollect ?
                R.drawable.sc : R.drawable.scw);
    }

}